import _ from 'lodash'

const words = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

/**
 * 获取列
 * @param {*} end
 * @returns 从 A 开始到 end
 */
function getExcelColsIndex(end) {
  if (end.length === 1) {
    return words.slice(0, words.indexOf(end) + 1).split('')
  } else {
    const arr = words.split('')
    const arr1 = words.slice(0, words.indexOf(end.charAt(1)) + 1).split('')
    const arr2 = arr1.map(i => {
      return 'A' + i
    })
    return arr.concat(arr2)
  }
}

// function getColIndex(word) {
//   return words.indexOf(word)
// }

/**
 * 工作簿转数组数据
 * @param {import('xlsx-js-style').WorkSheet} sheet 工作簿
 * @param {string} endCol 结束列号
 * @param {number} start 起始行数
 */
export function sheet2Data(sheet, endCol, start = 0) {
  const cols = getExcelColsIndex(endCol)
  const keyNumberRegExp = /[\w+](\d+)$/
  const maxRow = _.reduce(
    _.keys(sheet),
    (max, key) => {
      let [, row] = keyNumberRegExp.exec(key) || []

      if (row) {
        row = _.parseInt(row) + ''
        max = max < Number(row) ? Number(row) : max
      }

      return max
    },
    0
  )

  const tableData = []
  for (let rowIndex = start; rowIndex <= maxRow; rowIndex++) {
    const tableItem = []

    _.forEach(cols, colIndex => {
      const key = `${colIndex}${rowIndex}`
      tableItem.push(_.get(sheet[key], 'v', null))
    })

    tableData.push(tableItem)
  }

  return tableData
}
